/**
 * 快手店铺评分数据记录侧边栏组件
 */

import { StyleProvider } from "@ant-design/cssinjs"
import { FormOutlined } from "@ant-design/icons"
import cssText from "data-text:~/assets/css/dataScreenV2.css"
import antdResetCssText from "data-text:antd/dist/reset.css"
import ky from "ky"
import type { Options } from "ky"
import moment from "moment"
import type {
  PlasmoCSConfig,
  PlasmoGetInlineAnchor,
  PlasmoGetShadowHostId
} from "plasmo"
import React, { useEffect, useState } from "react"

import { usePort } from "@plasmohq/messaging/hook"
import { useStorage } from "@plasmohq/storage/dist/hook"

import { ThemeProvider } from "~theme"
import DyShopScoreDataDetailModal from "~ui_components/DyShopScoreDataDetailModal"
import { _callApi, getUserInfo } from "~utils/tools"

/******************
 快手的请求没有安全验证，可以直接请求，不需要使用api拦截和iframe构造获取
 ******************/

// 数据相关api请求列表
const apiList = [
  // 顶级数据请求
  {
    api: "getStoreScoreHomeV4",
    params: {
      __origin:"https://s.kwaixiaodian.com",
      __href:"https://s.kwaixiaodian.com/zone/governance-score/era/store-score-v4-pc",
      scoreSinkType:1
    },
    url: "https://s.kwaixiaodian.com/rest/app/tts/apollo/shopexp/kwaishopscore/queryDataFromKFlow"
  },
  // 商品体验级数据请求
  {
    api: "getIndexAndMathByDimCodeV4",
    params: { dimCode: 10 },
    url: "https://s.kwaixiaodian.com/rest/app/tts/apollo/shopexp/kwaishopscore/queryDataFromKFlow"
  },
  // 物流体验级数据请求
  {
    api: "getIndexAndMathByDimCodeV4",
    params: { dimCode: 11 },
    url: "https://s.kwaixiaodian.com/rest/app/tts/apollo/shopexp/kwaishopscore/queryDataFromKFlow"
  },
  // 售后服务级数据请求
  {
    api: "getIndexAndMathByDimCodeV4",
    params: { dimCode: 12 },
    url: "https://s.kwaixiaodian.com/rest/app/tts/apollo/shopexp/kwaishopscore/queryDataFromKFlow"
  }
]

// 注入配置
export const config: PlasmoCSConfig = {
  matches: [
    // 快手小店页面
    "https://s.kwaixiaodian.com/zone*"
  ],
  run_at: "document_start"
}

// 注入样式
export const getStyle = () => {
  const style = document.createElement("style")
  style.textContent = cssText + antdResetCssText
  return style
}

// 注入的shadow dom的id
export const HOST_ID = "tb-shop-score-tool"
export const getShadowHostId: PlasmoGetShadowHostId = () => HOST_ID

// export const getRootContainer = () => document.getElementById("app")
export const getInlineAnchor: PlasmoGetInlineAnchor = async () => {
  return {
    element: document.querySelector(
      "div#seller-main-pc-header > div > div > div:last-child > div:last-child"
    ),
    insertPosition: "afterbegin"
  }
}

// 组件定义
const TbShopScoreToolbar: React.FC = () => {
  // 评分数据处理port
  const scoreData = usePort("ksShopScoreData")
  // 数据完整性百分比
  const [dataCompleteRate, setDataCompleteRate] = useState<string>("0")
  // 用户是否登录
  const [userLogin] = useStorage("isLogin", false)
  const [showDetailModal, setShowDetailModal] = useState<boolean>(false)
  // 异常信息记录
  const [exceptionTxt, setExceptionTxt] = useState("")

  // 内部请求方法，发到后台处理
  const _ks_api_request = async (url: string, api: string, params: any) => {
    // 请求options
    const options = {
      searchParams: {
        api
      },
      json: {
        api,
        param: JSON.stringify(params)
      }
    }
    // 发送请求
    const res = await ky.post(url, options).json()
    // console.log(res)
    // 发送数据处理信息
    scoreData.send({
      api,
      action: "inspect",
      data: res
    })
  }

  // 获取数据键值总量
  const getKeysCount = async () => {
    const { data } = await _callApi("getKeysCountForDss", { shop_type: "ks" })
    scoreData.send({ action: "setKeys", data: data || 0 })
  }

  // 挂载事件监听
  useEffect(() => {
    // 获取数据键总量
    getKeysCount().then()
    // 挂载ui到服务
    // 初始化后台数据
    scoreData.send({ action: "clear" })
  }, [])

  // 数据抓取按钮触发方法
  const handleCaptureData = async () => {
    setExceptionTxt("数据抓取中...")
    // 模拟发送数据
    for (const item of apiList) {
      await _ks_api_request(item.url, item.api, item.params)
    }
  }

  // 数据显示对话框点击显示
  const handleShowDetailModal = () => {
    setShowDetailModal(true)
  }

  // 数据显示对话框关闭方法
  const handleClose = () => {
    setShowDetailModal(false)
  }

  // 数据清空方法
  const handleClear = () => {
    scoreData.send({
      action: "clear"
    })
    setExceptionTxt(``)
  }

  useEffect(() => {
    const rate = scoreData.data?.rate || "0"
    if (Number(rate) >= 100) {
      // 数据完整，触发删除iframe事件
      window.dispatchEvent(new Event("tbScoreIframeDelete"))
      // 设置结束信息
      // 数据日期
      const scoreDate = scoreData.data?.data["日期"] || ""
      setExceptionTxt(`数据抓取完成! 数据日期：【${scoreDate}】`)
    }
    // 数据完整率
    setDataCompleteRate(rate)
  }, [scoreData.data])

  return (
    <ThemeProvider>
      <StyleProvider container={document.getElementById(HOST_ID).shadowRoot}>
        {userLogin ? (
          <div
            className={
              "dy-shop-score-tool-wrapper ks-shop-score-tool-wrapper-fixed"
            }>
            <div className={"button-item"} onClick={handleShowDetailModal}>
              <FormOutlined />
            </div>
            {/*文字描述*/}
            <div className={"button-text"}>
              <span>评分数据</span>
            </div>
            {/*数据完整度*/}
            <div className={"button-tip"}>
              <span>{dataCompleteRate}%</span>
            </div>
          </div>
        ) : null}
        <DyShopScoreDataDetailModal
          shopType={"ks"}
          keys={scoreData?.data?.keysList}
          showDetailModal={showDetailModal}
          handleClose={handleClose}
          dataObject={scoreData?.data?.data}
          dataCompleteRate={dataCompleteRate}
          exceptionTxt={exceptionTxt}
          handleClear={handleClear}
          handleCapture={handleCaptureData}
        />
      </StyleProvider>
    </ThemeProvider>
  )
}

export default TbShopScoreToolbar
